<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-24
 * Time: 15:06
 */
namespace App\Http\Middleware;

use App\Models\Admin;
use Closure;
use Route, Response;
use DB;

class CheckAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed  权限验证
     */
    public function handle($request,Closure $next, $guard = null)
    {

        //判断是否设置别名
        //$routename = Route::currentRouteName();//路由别名
        $routeAction = $request->route()->getAction();
        $routename = $routeAction['as'];
        if(empty($routename)){
            return $next($request);
        }

        $data = $request->input();
        if($data['user']['guard'] == 'member'){
            return Response::Json(['code' => '-1', 'message' => '您无权限进行此操作']);
        }


        $adminModel = new Admin();
        $admin = $adminModel->where('id',$data['user']['uid'])->first();
        if($admin->id ==  1){
            return $next($request);
        }

        $auth = DB::table('permissions')->where('name',$routename)->first(['name']);
        if(empty($auth)){
            return $next($request);
        }

        //权限查看
        if($admin->can($routename)){
            return $next($request);
        }else{
            return Response::Json(['code' => '-1', 'message' => '您无权限进行此操作']);
        }
    }
}
